<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model
{
    private $user_info          = 'fe_user_info';
    private $fe_users_table_name          = 'fe_users';
    private $user_collect          = 'fe_user_collect';
    private $topic_table_name   = 'topic';
    private $post_table_name   = 'post';
    private $fe_post_table_name   = 'fe_post';
    private $error = array();
    private $default_category;
    private $default_category_alias;
    function __construct()
    {
        parent::__construct();
        $ci =& get_instance();
        $this->default_category = $ci->config->item('category', 'layout');
        $this->default_category_alias = $ci->config->item('category_alias', 'layout');
    }
    
    function checkIfUserSetUp($login_info){
        
        $this->db->where('email', $login_info['email']);
        $this->db->where('account_type', $login_info['account_type']);
        
        $user_info = $this->db->get($this->user_info);
        
        if($user_info->num_rows()==0){
            /*
             * 表示user是第一次登入
             * 所以要先塞default category
             */
            
            if($this->setUpUserDefaultData($login_info)){
                return true;    
            }
            else{
                return false;   
            }
        }
        else{
            return false;
        }
    }

    function show_user_collect(){
        $this->db->select('collects');
        $query = $this->db->get($this->user_collect);
        $result = $query->result_array();
        $result_array = array();
        $categoried_result = array();
        foreach ($result as $key => $value) {
            $result_array = urldecode($value['collects']);
            $result_array = json_decode($result_array,true);
            //echo "<pre>";print_r($result_array);echo "</pre>";
            foreach($result_array as $k=> $v){
                if(isset($categoried_result[$k])){
                    $categoried_result[$k] += count($v);
                }
                else{
                    $categoried_result[$k] = 0;
                    $categoried_result[$k] += count($v);
                }
            }
        }
        
        echo "<pre>";print_r($categoried_result);echo "</pre>";
    }

    function setUpUserDefaultData($login_info){
        
        $user_info = array('uid'=>$login_info['id'], 'gender'=>$login_info['gender'], 'first_name'=>$login_info['first_name'], 'last_name'=>$login_info['last_name'], 'email'=>$login_info['email'], 'account_type'=>$login_info['account_type'], 'name'=>$login_info['name'], 'link'=>$login_info['link'] );
        $this->db->insert($this->user_info, $user_info); 
        
        if($this->db->_error_number()==0){
            
            $user_category = array();
            $category_alias = array();
            foreach ($this->default_category_alias as $key => $value) {
                $user_category[$key] = array();
            }

            $user_category = json_encode($user_category);
            $user_category = urlencode($user_category);

            $category_alias = $this->default_category_alias;
            $category_alias = json_encode($category_alias);
            $category_alias = urlencode($category_alias);

            $user_collect = array('uid'=>$login_info['id'],'collects'=>$user_category,'collect_alias'=>$category_alias);
            $this->db->insert($this->user_collect, $user_collect); 
            if($this->db->_error_number()==0){
                return true;
            }
            else{
                return false;
            }
        }
        else{
            return false;
        }
    }
    function selectUserCollects($uid){
        $this->db->where('uid',$uid);
        $query = $this->db->get($this->user_collect);
        if ($query->num_rows() > 0){
            return $query->result_array();
        }
        else{
            return false;
        }
    }

    function selectUserShares($uid){
        $this->db->where('user_id',$uid);
        $this->db->where('status','1');
        $this->db->order_by("modified_time", "desc");
        $query = $this->db->get($this->fe_post_table_name
            );
        if ($query->num_rows() > 0){
            return $query->result_array();
        }
        else{
            return false;
        }
    }

    function getCollectsDetailByIDString($TopicIDString,$PostIDString){
        echo $PostIDString;
        echo "<br />";
        echo $TopicIDString;exit;
    }

    function insertNewCategory($uid,$new_category){

        if($existRecord = $this->checkIfExist($uid)){ // collect record exists
            
            $collects = $existRecord[0]->collects;
            $collects = urldecode($collects);
            $collects = json_decode($collects);
            
            $new_category_alias = $new_category;
            $replace_array = array('/','(',')');
            $new_category = str_replace($replace_array, '', $new_category);
            
            if(isset($collects->$new_category)){ // duplicate category
                return '5';exit;
            }

            //update collects
            $collects->$new_category = array(); // make new category array
            $collectsArrayObject = new ArrayObject($collects);
            $collectsArrayObject->ksort(); 
            $collects = json_encode($collects);
            $collects = urlencode($collects);
            
            //update collect alias
            $this->db->select('collect_alias');
            $this->db->where('uid',$uid);
            $query = $this->db->get($this->user_collect);
            $collect_alias = $query->result();
            $collect_alias = $collect_alias[0]->collect_alias;
            $collect_alias = urldecode($collect_alias);
            $collect_alias = json_decode($collect_alias);
            //echo "<pre>";print_r($collect_alias);echo "</pre>";exit;
            
            
            $collect_alias->$new_category = $new_category_alias;
            $collect_alias = json_encode($collect_alias);
            $collect_alias = urlencode($collect_alias);
            
            $user_info = array('collects'=>$collects,'collect_alias'=>$collect_alias);
            $this->db->where('uid', $uid);
            $this->db->update($this->user_collect, $user_info); 
            
            if($this->db->_error_number()==0){
                return '1';
            }
            else{
                return '2';
            }
        }
        else{ // there is no any record
            $collects = array();
            $collects[$new_category] = array();
            $collects = json_encode($collects);
            $collects = urlencode($collects);
            $user_info = array('uid'=>$uid, 'collects'=>$collects);
            $this->db->insert($this->user_collect, $user_info); 

            if($this->db->_error_number()==0){
                return '1';
            }
            else{
                return '2';
            }
        }

        
    }

    function checkIfExist($uid){
        $this->db->where('uid',$uid);
        $query = $this->db->get($this->user_collect);
        if ($query->num_rows() > 0){
            return $query->result();
        }
        else{
            return false;
        }
    }

    function updateUserCollects($uid,$collects){
        $user_info = array('collects'=>$collects);
        $this->db->where('uid', $uid);
        $this->db->update($this->user_collect, $user_info); 
            
        if($this->db->_error_number()==0){
            return true;
        }
        else{
            return false;
        }
    }

    function changeCategoryName($uid,$collects,$collect_alias){
        $user_info = array('collects'=>$collects,'collect_alias'=>$collect_alias);
        $this->db->where('uid', $uid);
        $this->db->update($this->user_collect, $user_info); 
            
        if($this->db->_error_number()==0){
            return true;
        }
        else{
            return false;
        }
    }

    function get_left_join_count($activity_id){
        $array = array($this->activity_pool_table_name.'.activity_id' => $activity_id,$this->activity_pool_table_name.'.kind' => 'wanna_join');
        $this->db->select('*');
        $this->db->join($this->activity_info_table_name, $this->activity_pool_table_name.'.activity_id = '.$this->activity_info_table_name.'.activity_id');
        $this->db->from($this->activity_pool_table_name);
        $this->db->where($array);
        $query = $this->db->get();
        $now_wanna_join_count = $query->num_rows();
        
        if($now_wanna_join_count == 0){
            return array('left_join_count'=>'FALSE','wanna_join_count'=>0);
        }
        
        $temp = $query->result();
        
        $join_activity = $temp[0];
        $max_join_p = $join_activity->activity_max_p;
        $left_join_count = $max_join_p - $now_wanna_join_count;
        
        return array('left_join_count'=>$left_join_count,'wanna_join_count'=>$now_wanna_join_count);
    }

    function updateUserName($uid,$new_username){

        $this->db->where('uid !=', $uid);
        $this->db->where('LOWER(name)=', strtolower($new_username));
        $query = $this->db->get($this->user_info);

        if ($query->num_rows() >= 1){
            return '2'; // duplicated username
        }
        else{
            $user_info = array('username'=>$new_username);
            $this->db->where('id', $uid);
            $this->db->update($this->fe_users_table_name, $user_info); 

            $user_info = array('name'=>$new_username);
            $this->db->where('uid', $uid);
            $this->db->update($this->user_info, $user_info);  

            if($this->db->_error_number()==0){
                return true;
            }
            else{
                return false;
            }
        }
    }

    function checkFBUserSession($uid,$newdata){
        $this->db->where('uid', $uid);
        $query = $this->db->get($this->user_info);

        if ($query->num_rows() == 1){ // 用原記錄覆蓋session data
            $row = $query->row();
            $newdata['LOGIN_INFO']['name'] = $row->name;
        }
        
        return $newdata;
    }

}
